--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

    生命量产

]]--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local Widget = require "widgets/widget"
local Image = require "widgets/image" -- 引入image控件
local UIAnim = require "widgets/uianim"
local ImageButton = require "widgets/imagebutton"
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local assets =
{
    -- Asset("ANIM", "anim/cane.zip"),
    -- Asset("ANIM", "anim/swap_cane.zip"),
}

local function stop_move(player)
    if player.components.locomotor then
        player.components.locomotor:Stop()
    end    
end

local function spell_com_install(inst)
    inst:ListenForEvent("Loramia_OnEntityReplicated.loramia_com_item_spell",function(inst,replica_com)
        replica_com:Set_Dotted_Circle_Radius(10)
        replica_com:Set_Mouse_Left_Click_Fn(function(inst,owner,pt,target)
                        --- 往物品自身发送event
                        replica_com:PushEvent("left_clicked",{pt = pt})
                        stop_move(owner)
        end)
        replica_com:Set_Mouse_Right_Click_Fn(function(inst,owner,pt,target)
                        --- 往物品自身发送event
                        replica_com:PushEvent("right_clicked",{pt = pt})
        end)
        -- replica_com.indicator_type = "arrow" -- "circle" or "arrow"
    end)
    if not TheWorld.ismastersim then
        return
    end
    inst:AddComponent("loramia_com_item_spell")
    inst.components.loramia_com_item_spell:SetNeed2CloseController(false)
    -----------------------------------------------------------------------------
    ---
        inst.components.loramia_com_item_spell:SetTestFn(function(inst,doer)
            if not doer.components.loramia_com_talent_tree:IsUnlocked("life_mass_production")   -- 技能是否解锁
            then
                return false
            end
            ----------------------------------------------------
            --- 判断是否已经拥有3个工人
                -- local worker_num = 0
                -- for follower, flag in pairs(doer.components.leader.followers) do
                --     if follower and flag and follower:IsValid() and follower:HasTag("loramia_worker") then
                --         worker_num = worker_num + 1
                --     end
                -- end
                -- if worker_num >= 3 then
                --     return false
                -- end
            ----------------------------------------------------
            return true
        end)
    -----------------------------------------------------------------------------
    ---
        inst:ListenForEvent("left_clicked",function(inst,_table)
            -- print("left_clicked 生命量产 +++++++++++++++ ",_table.pt.x,_table.pt.y,_table.pt.z)
            local player = inst.components.loramia_com_item_spell:GetOwner()
            -- player.components.locomotor:Stop()
            stop_move(player)
            -- local points = TUNING.LORAMIA_FN:GetSurroundPoints({
            --     target = _table.pt,
            --     range = 6,
            --     num = 3
            -- })
            -- local worker_prefabs = {"shadowlumber","shadowminer","shadowdigger"}
            -- for i = 1,#points do
            --     local point = points[i]
            --     local prefab = worker_prefabs[i]
            --     SpawnPrefab("spawn_fx_small").Transform:SetPosition(point.x,0,point.z)
            --     local pet = SpawnPrefab(prefab)
            --     pet.Transform:SetPosition(point.x, 0,point.z)
            --     player.components.leader:AddFollower(pet)
            --     pet:AddDebuff("loramia_spell_mass_production_for_life_debuff","loramia_spell_mass_production_for_life_debuff")
            --     pet.sg:GoToState("idle")
            -- end
            player:PushEvent("loramia_spell_mass_production_for_life_acitved",_table.pt)
            inst:Remove()
        end)
        inst:ListenForEvent("right_clicked",function(inst,_table)
            inst:Remove()
            -- print("取消技能")
        end)
    -----------------------------------------------------------------------------
end

local function fn()
    local inst = CreateEntity()
    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()
    inst.entity:SetPristine()
    spell_com_install(inst)
    return inst
end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- acceptable
    local item_and_target = {
        ["pickaxe"] = "shadowminer",
        ["shovel"] = "shadowdigger",
        ["axe"] = "shadowlumber",        
    }
    local function acceptable_install_in_client(inst)
        -- local test_num = 30
        -- inst.___acceptable_install_in_client_task = inst:DoPeriodicTask(1,function()
        --     local target = inst.entity:GetParent()
        --     if target and ThePlayer and target:HasTag(ThePlayer.userid) then
        --         target:DoPeriodicTask(1,function()
        --             local acitve_item = ThePlayer.replica.inventory:GetActiveItem()
        --             if acitve_item and item_and_target[acitve_item.prefab] then
        --                 target:RemoveTag("NOCLICK")
        --                 return
        --             end                    
        --             target:AddTag("NOCLICK")
        --         end)
        --         inst.___acceptable_install_in_client_task:Cancel()
        --     end
        --     test_num = test_num - 1
        --     if test_num <= 0 then
        --         inst.___acceptable_install_in_client_task:Cancel()
        --     end
        -- end)
    end
    local function acceptable_test(inst, item, giver, count)
        return item and item_and_target[item.prefab] ~= nil and item_and_target[item.prefab] ~= inst.prefab
    end
    local function acceptable_on_accept(inst, giver, item, count)
        local target_prefab = item_and_target[item.prefab]
        print("66666",target_prefab,inst.worker_index)
        local leader = inst.components.follower:GetLeader()
        if leader then
            leader:PushEvent("loramia_spell_mass_production_for_life_type_change",{
                target = inst,
                target_prefab = target_prefab,                
            })
            item:Remove()
        end
    end
    local function acceptable_install_in_server(inst)
        inst:AddComponent("trader")
        inst.components.trader:SetAcceptTest(acceptable_test)
        inst.components.trader:SetOnAccept(acceptable_on_accept)
        inst.components.trader.deleteitemonaccept = false
        -- inst:RemoveTag("NOCLICK")
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- debuff
    local function debuff_on_attach(inst,target)
        ----------------------------------------------------
        ---
            inst.entity:SetParent(target.entity)
            inst.Transform:SetPosition(0,0,0)
        ----------------------------------------------------
        --- leader
            local leader = target.components.follower:GetLeader()
            if leader == nil then                
                target:Remove()
                return
            end
        ----------------------------------------------------
        --- 修改外观
            if target.components.skinner == nil then
                target:AddComponent("skinner")
            end
            -- target.components.skinner:SetSkinName("loramia_none")
            target.AnimState:SetMultColour(1,1,1,1)
            target.AnimState:SetBuild("llmy")
        ----------------------------------------------------
        --- 修改血量
            if target.components.health then
                target.components.health:SetMaxHealth(1000)
                inst:DoPeriodicTask(1,function()
                    target.components.health:DoDelta(1,true)
                end)
            end
        ----------------------------------------------------
        --- 持续时间
            if target.components.timer then
                inst:DoPeriodicTask(5,function()
                    for timer_name, v in pairs(target.components.timer.timers) do
                        target.components.timer:PauseTimer(timer_name)
                    end
                end)
            end
            local MAX_TIME = 8*60   -- 8分钟
            inst:DoPeriodicTask(1,function()
                if inst.components.loramia_data:Add("timer",1) >= MAX_TIME then
                    target:StopBrain()
                    target:SetBrain(nil)
                    target.components.health:Kill()
                end
            end)
        ----------------------------------------------------
        --- 执行靠近
            inst:ListenForEvent("close2player",function()
                local points = TUNING.LORAMIA_FN:GetSurroundPoints({
                    target = leader,
                    range = 6,
                    num = 8
                })
                local pt = points[math.random(#points)]
                target.Transform:SetPosition(pt.x,0,pt.z)
                SpawnPrefab("spawn_fx_small").Transform:SetPosition(pt.x,0,pt.z)
                target:RestartBrain()
            end)
        ----------------------------------------------------
        --- 超出加载范围
            target:ListenForEvent("entitysleep",function()
                inst:PushEvent("close2player")
                OnEntityWake(target.GUID)
            end)
        ----------------------------------------------------
        --- 距离检查
            local MAX_RANGE_SQ = 30*30
            local checker_fn = function()
                if target:GetDistanceSqToInst(leader) > MAX_RANGE_SQ then
                    inst:PushEvent("close2player")
                end
            end
            target:DoPeriodicTask(3,function()
                pcall(checker_fn)
            end)
        ----------------------------------------------------
        --- tag
            target:AddTag("loramia_worker")
            target:AddTag("companion")
            target:AddTag(tostring(leader.userid))
            target:RemoveTag("NOCLICK")
        ----------------------------------------------------
        ---- 链接
            leader:PushEvent("loramia_spell_mass_production_for_life_link",target)
        ----------------------------------------------------
        ---- 击杀掉落
            if target.components.lootdropper == nil then
                target:AddComponent("lootdropper")
            end
            -- target:ListenForEvent("death",function()
            --     target.components.lootdropper:SpawnLootPrefab("nightmarefuel")
            -- end)
        ----------------------------------------------------
        --- 切换类型
            target:ListenForEvent("switch",function(_,prefab)
                leader:PushEvent("loramia_spell_mass_production_for_life_type_change",{
                    target = target,
                    target_prefab = prefab,
                })
            end)
        ----------------------------------------------------
        --- 物品接受
            acceptable_install_in_server(target)
        ----------------------------------------------------
    end



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    local function debuff()
        local inst = CreateEntity()

        inst.entity:AddTransform()
        inst.entity:AddNetwork()
        inst.entity:AddTransform()
        inst:AddTag("CLASSIFIED")

        inst.entity:SetPristine()
        -- switch_hud_install(inst)
        acceptable_install_in_client(inst)
        if not TheWorld.ismastersim then
            return inst
        end

        inst:AddComponent("loramia_data")
        inst:AddComponent("debuff")
        inst.components.debuff:SetAttachedFn(debuff_on_attach)
        inst.components.debuff.keepondespawn = true -- 是否保持debuff 到下次登陆

        return inst
    end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return Prefab("loramia_spell_mass_production_for_life", fn, assets),
    Prefab("loramia_spell_mass_production_for_life_debuff", debuff, assets)
